package music

import javafx.scene.media.Media
import javax.sound.sampled.AudioFormat
import javafx.scene.media.MediaPlayer
import java.net.URL
import java.io.File
import java.net.URI
import scala.actors._
import scala.actors.Actor
import scala.actors.Actor._
import scala.actors.remote._
import scala.actors.remote.RemoteActor._
import music.Messages._
import music.player.SoundPlayer
import scala.concurrent.ops._
import music.library.Library



object Formats {
  val wavFormat:AudioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100, 16, 2, 4, 44100, false)
  def WAV:AudioFormat = wavFormat;
}

//TODO(0) O:PlayQueue (Clear, AddSong, AddPlaylist/Group, RemoveSong, ReOrder, CheckDuplicates)
//TODO(0) C:Playlists (AddSong, RemoveSong, Reorder, CheckDuplicates)
//TODO(0) PlayQueue -> New Playlist / Update Playlist
//TODO(0) C:Song ("Unique" ID, Metadata)
//TODO(0) C:LibraryIndex i.e. views on a library
//TODO(0) C:Song Variant (Tags, TimeCommands, Owner)
//TODO(0) O:Visualizer API


/*
 * Events (Records that can be used but harder to get to?) vs. Playlists (actively work on these)
 * 
 */

object Main {
  
  def main(args: Array[String]): Unit = {
    println("Hello World");
    
    SoundPlayer.start();
    
    while(true)
    {
      // handle CIN
      if(Console.in.ready()) {
        val cin:String = Console.in.readLine();
	    val pieces:List[String] = cin.split(" ").toList;
	    pieces.head match {
	      case "PLAY" => { 
	        if(pieces.tail == Nil) {
	          SoundPlayer ! M_RESUME_SONG; 
	        } else {
	          try {
	            val file:File = new File(pieces(1));
	            SoundPlayer ! M_PLAY_SONG(file);
	          } catch { case e:Error => println("ERR:" + e.getMessage())}
			 }
	      }
	      case "SCAN" => println(Library.scanFolder(new File("Songs")));
	      case "PAUSE" => SoundPlayer ! M_PAUSE_SONG;
	      case "STOP" => SoundPlayer ! M_STOP_SONG;
	      case "RESUME" => SoundPlayer ! M_RESUME_SONG;
	      //case "INFO" => getInfo(pieces(1));
	      case "VOLUME" => {
	        val d:Double = pieces(1).toDouble;
	        if(d<0 || d > 1) { 
	          println("Please provide a volume between 0 and 1.")
	        } else {
	          SoundPlayer ! M_SET_VOLUME(d);
	        }
	      }
	      case "QUIT" => { System.exit(1); }
	      case "SEEK" => {
	        val x = pieces(1);
	        if(x.indexOf("%") > 0) {
	          val p = x.substring(0, x.indexOf('%'));
	          SoundPlayer ! M_SEEK_SONG_PERCENT(p.toDouble);
	        } else {
	          SoundPlayer ! M_SEEK_SONG_S(x.toDouble);
	        }
	        
	      }
	      case default => printHelp();  
	    }
      }
    }
    
  }
  
  def printHelp():Unit = {
    println(
"""
Commands:
 - PLAY <song>
 - INFO <song>
 - QUIT""")
    
  }
  
  
}